
cd $rspath 

global firstyear 1996
global lastyear 2006

use rs_baseline_id_conc$firstyear$lastyear, clear 
keep hs6 rs_hs6* 
egen p=group(hs6)
save temp.dta, replace

use temp.dta, clear					
collapse (mean) rs_hs6_se rs_hs6_b , by(p hs6_2002)
save temp.dta, replace

keep if hs6==""
save tmp_rs.dta, replace


forvalues i=1/5077 {
use temp.dta , replace 
keep if p==`i' 
dis "`i'"
qui sum rs_hs6_b 
local m=r(mean) 
qui sum rs_hs6_se 
local sd=r(mean) 
drawnorm rsbs, n(400) means(`m') sds(`sd') clear
g n=_n
g p=`i'
qui greshape wide rsbs,  i(p)  j(n) 
append using  tmp_rs
qui save tmp_rs, replace

}

use tmp_rs, clear
drop rs_hs6_se rs_hs6_b hs6_2002
merge 1:1 p using  temp.dta
drop _m 
save tmp_rs, replace

/*
use ./tmp_rs, clear
keep rsbs* //  rsbs1 rsbs2 rsbs3 rsbs4 

matrix accum R = rsbs*, nocons dev
matrix R = corr(R)
matrix I=J(400,1,1)		
matrix D=diag(I) 
matrix R2=R - D 
matrix Mean=((I'*R2)*I)/(400*400 - 400)

mata: R2_=st_matrix("R2")
mata 
E2=R2_:*R2_
st_matrix("E2",E2)
end

matrix E2_=((I'*E2)*I)/(400*400 - 400)
matrix Var=E2_-Mean*Mean 

matlist Mean 

clear matrix 
